<?php
error_reporting(-1);
include './classes/Auth.class.php';
include './classes/AjaxRequest.class.php';

if (!empty($_COOKIE['sid']))
{
    // check session id in cookies
    session_id($_COOKIE['sid']);
}
session_start();

class AuthorizationAjaxRequest extends AjaxRequest
{
    public $actions = array(
        "login" => "login",
        "logout" => "logout",
        "register" => "register",
    );

    public function login()
    {
		require_once './includes/parselang.php';
        if ($_SERVER["REQUEST_METHOD"] !== "POST") 
		{
            // Method Not Allowed
            http_response_code(405);
            header("Allow: POST");
            $this->setFieldError("main", "Method Not Allowed");
            return;
        }
        setcookie("sid", "");

        $username = $this->getRequestParam("username");
        $password = $this->getRequestParam("password");
        $remember = !!$this->getRequestParam("remember-me");
   				
		if (empty($username)) 
		{
            $this->setFieldError("username", $lang['enterName']);
            return;
        }
		
		if (empty($password)) 
		{
            $this->setFieldError("password", $lang['enterPass']);
            return;
        }

        $user = new Battlelog\User(); //создается объект $user родительского  класса Auth 'Auth.class.php'
		//Для того, чтобы проверить правильность ввода логина и пароля, используется метод authorize
        $auth_result = $user->authorize($username, $password, $remember); 

        if (!$auth_result) 
		{
            $this->setFieldError("password", $lang['wrongLogin']);
            return;
        }

        $this->status = "ok";
        $this->setResponse("redirect", ".");
        $this->message = sprintf("Hello, %s! Access granted.", $username);
    }

    public function logout()
    {
        if ($_SERVER["REQUEST_METHOD"] !== "POST") {
            // Method Not Allowed
            http_response_code(405);
            header("Allow: POST");
            $this->setFieldError("main", "Method Not Allowed");
            return;
        }

        setcookie("sid", "");

        $user = new Battlelog\User();
        $user->logout();

        $this->setResponse("redirect", ".");
        $this->status = "ok";
    }

    public function register()
    {
		require_once './includes/parselang.php';
        if ($_SERVER["REQUEST_METHOD"] !== "POST") 
		{
            // Method Not Allowed
            http_response_code(405);
            header("Allow: POST");
            $this->setFieldError("main", "Method Not Allowed");
            return;
        }

        setcookie("sid", "");

        $username = $this->getRequestParam("username");
        $password1 = $this->getRequestParam("password1");
        $password2 = $this->getRequestParam("password2");
		
        if (empty($username)) {
            $this->setFieldError("username", $lang['enterName']);
            return;
        }

        if (empty($password1)) {
            $this->setFieldError("password1", $lang['enterPass']);
            return;
        }

        if (empty($password2)) {
            $this->setFieldError("password2", $lang['confirmPass']);
            return;
        }

        if ($password1 !== $password2) {
            $this->setFieldError("password2", $lang['passNotMatch']);
            return;
        }
		
		if (!preg_match ("/^.[0-9a-z_ ]{3,16}$/i", $username) )
		{
			$this->setFieldError("username", $lang['incorrectName']);
            return;
		}
						
		if (!preg_match ("/^.[0-9a-z_]{3,16}$/i", $password1) )
		{
			$this->setFieldError("username", $lang['incorrectPass']);
            return;
		}
		
		if (strlen(strstr($username, 'admin'))>0) 
		{
			$this->setFieldError("username", $lang['unacceptebleName']);
            return;
		}
		
		if (strlen(strstr($username, 'Admin')) > 0) 
		{
			$this->setFieldError("username", $lang['unacceptebleName']);
            return;
		}
		/*		
		if (strpos($username, 'admin') == true)
		{
			$this->setFieldError("username", $lang['unacceptebleName']);
            return;
		}
		*/
        $user = new Battlelog\User();
        try 
		{
            $new_user_id = $user->create($username, $password1);
        }
		catch (\Exception $e) 
		{
            $this->setFieldError("username", $e->getMessage());
            return;
        }
        $user->authorize($username, $password1);

        $this->message = sprintf("Hello, %s! Thank you for registration.", $username);
        $this->setResponse("redirect", "/");
        $this->status = "ok";
    }
}

$ajaxRequest = new AuthorizationAjaxRequest($_REQUEST);  //создается объект $ajaxRequest от класс AuthorizationAjaxRequest
$ajaxRequest->showResponse();
